package com.netflexitysolutions.amazonws.s3.internal.interceptors;

import com.netflexitysolutions.amazonws.s3.wrapper.PutObjectWrapper;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import org.apache.cxf.attachment.AttachmentImpl;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.interceptor.AttachmentOutInterceptor;
import org.apache.cxf.message.Attachment;
import org.apache.cxf.message.Message;

public class PutObjectAttachmentInterceptor extends AttachmentOutInterceptor {

    public void handleMessage(Message message){
        System.out.println(this.getClass().getCanonicalName() + " interceptor call");
        SoapMessage sm = (SoapMessage)message;
        List pow = sm.getMessage().getContent(List.class);
        if(pow != null){
            for(Object obj : pow){
                if(obj instanceof PutObjectWrapper){
                    System.out.println("PutObject");
                    File is = ((PutObjectWrapper)obj).getIs();
                    AttachmentImpl att = new AttachmentImpl("", new DataHandler(new FileDataSource(is)));
                    att.setXOP(true);
                    Collection atm = sm.getMessage().getAttachments();
                    if(atm == null){
                       atm = new ArrayList<Attachment>();
                       sm.getMessage().setAttachments(atm);
                    }
                    atm.add(att);

                }
            }
        }
    }
}
